﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CheckOutEngine.cs" company="DST Nexdox">
//   Copyright (c) DST Nexdox. All rights reserved.
// </copyright>
// <summary>
//   Defines the CheckOutEngine type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace BusinessEngines
{
  using System;
  using BusinessEngineInterfaces;
  using Entities;
  using Exceptions;
  using ServiceInterfaces;
  using UnityRepository.Interfaces;

  public class CheckOutEngine : ICheckOutEngine
  {
    private readonly ICheckOutRepository checkOutRepository;
    private readonly IDocumentService documentService;

    public CheckOutEngine(ICheckOutRepository checkOutRepository, IDocumentService documentService)
    {
      this.checkOutRepository = checkOutRepository;
      this.documentService = documentService;
    }

    public Boolean IsDocumentCheckedOut(String documentId)
    {
      CheckOut currentCheckOut = this.checkOutRepository.GetCheckOut(documentId);
      return currentCheckOut != null;
    }

    public CheckOut CheckOutDocument(String userName, Int32 docId)
    {
      var checkOut = new CheckOut
      {
        CheckOutBy = userName,
        CheckOutDate = DateTime.Now,
        DocumentId = docId
      };

      this.checkOutRepository.Create(checkOut);
      return checkOut;
    }

    public CheckOut CheckOutDocument(String userName, String documentId)
    {
      var document = this.documentService.GetDocument(documentId);
      if (document == null)
      {
        throw new UnableToRetrieveDocumentException(String.Format("Unable to retrieve document {0}", documentId));
      }

      return this.CheckOutDocument(userName, document.Id);
    }
  }
}
